package com.example.apollotogit.config;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.apollotogit.service.HandleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.listener.PatternTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.listener.Topic;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.TimeUnit;

/**
 * @author hy
 * @createTime 2021-05-01 08:53:19
 * @description 期望是可以监听某个key的变化，而不是失效
 */
public class RedisKeyChangeListener implements MessageListener/* extends KeyspaceEventMessageListener */ {
    @Autowired
    RedisClient redisClient;

    @Autowired
    private HandleService handleService;


    private final String listenerKeyName; // 监听的key的名称
    private static final Topic TOPIC_ALL_KEYEVENTS = new PatternTopic("__keyevent@*"); //表示只监听所有的key
    private static final Topic TOPIC_KEYEVENTS_SET = new PatternTopic("__keyevent@0__:set"); //表示只监听所有的key
    private static final Topic TOPIC_KEYNAMESPACE_NAME = new PatternTopic("__keyspace@0__:APOLLOTOGITMQ"); // 不生效
    private static Topic TOPIC_KEYNAMESPACE_NAME1 = null; // 不生效
    // 监控
    private static final Topic TOPIC_KEYEVENTS_NAME_SET_USELESS = new PatternTopic("__keyevent@0__:set myKey");
    private String keyspaceNotificationsConfigParameter = "KEA";

    public RedisKeyChangeListener(RedisMessageListenerContainer listenerContainer, String listenerKeyName) {
        this.listenerKeyName = listenerKeyName;
        TOPIC_KEYNAMESPACE_NAME1 = new PatternTopic("__keyspace@0__:" + listenerKeyName);
        initAndSetRedisConfig(listenerContainer);
    }

    public RedisKeyChangeListener(String listenerKeyName) {
        this.listenerKeyName = listenerKeyName;
    }

    public void initAndSetRedisConfig(RedisMessageListenerContainer listenerContainer) {

        if (StringUtils.hasText(keyspaceNotificationsConfigParameter)) {

            RedisConnection connection = listenerContainer.getConnectionFactory().getConnection();

            try {

                Properties config = connection.getConfig("notify-keyspace-events");

                if (!StringUtils.hasText(config.getProperty("notify-keyspace-events"))) {
                    connection.setConfig("notify-keyspace-events", keyspaceNotificationsConfigParameter);
                }

            } finally {
                connection.close();
            }
        }
        // 注册消息监听
        listenerContainer.addMessageListener(this, TOPIC_KEYNAMESPACE_NAME1);
    }


    @Override
    public synchronized void onMessage(Message message, byte[] pattern) {
        /*if(message.toString().equals("lpush")) {
            byte[] body = message.getChannel();
            String string = new String(body, Charset.forName("utf-8"));
            //获取监听keyname
            String keyName = string.split(":")[1];
            Long size = redisClient.getSize(keyName);
            System.out.println("redis size = " + size);
            //监听到key值变化，判断key是否含有值
            if (size > 0) {
                for (Long i = size; i > 0; i--) {
                    String s = (String) this.redisClient.brpop(keyName, 0, TimeUnit.SECONDS);
//                    System.out.println("s = " + s);
                    Map map1 = (Map)JSON.parse(s);
//                    JSONObject jsonObject = JSONObject.parseObject(s);
*//*                    Map<String, Object> map = new HashMap<>();
                    //循环转换
                    for (Map.Entry<String, Object> entry : jsonObject.entrySet()) {
                        map.put(entry.getKey(), entry.getValue());
                    }*//*
                    //判断参数是否为空
                    if (!map1.isEmpty()) {
                        System.out.println("start solve");
                        //调用逻辑进行自动拉取
                        try {
//                            System.out.println(map1);
                            handleService.getPrintInfo(map1);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }*/
    }

}